﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Synchronization.Data;
using VendorProducts.NorthwindDataSetTableAdapters;

namespace VendorProducts
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private NorthwindDataSet _northwindDataSet;
		private ProductsTableAdapter _northwindDataSetTableAdapter = new ProductsTableAdapter();

		public MainWindow()
		{
			InitializeComponent();
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			_northwindDataSet = (NorthwindDataSet) (FindResource("northwindDataSet"));
			// Load data into the table Products. You can modify this code as needed.
			_northwindDataSetTableAdapter.Fill(_northwindDataSet.Products);
			SyncData();
			var productsViewSource = (CollectionViewSource) (FindResource("productsViewSource"));
			productsViewSource.View.MoveCurrentToFirst();
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			SyncData();
		}

		private void mnuSave_Click(object sender, RoutedEventArgs e)
		{
			_northwindDataSetTableAdapter.Update(_northwindDataSet.Products);
			MessageBox.Show("Saved");
		}

		private void mnuExit_Click(object sender, RoutedEventArgs e)
		{
			Application.Current.Shutdown();
		}

		private void SyncData()
		{
			try
			{
				var syncAgent = new NorthwindLocalDataCacheSyncAgent {Products = {SyncDirection = SyncDirection.Bidirectional}};
				var syncStats = syncAgent.Synchronize();
				_northwindDataSet.Products.Merge(_northwindDataSetTableAdapter.GetData());
				EventLog.WriteEntry("VendorProducts", "Syncronized Successfully", EventLogEntryType.Information);
			}
			catch (Exception ex)
			{
				EventLog.WriteEntry("VendorProducts", "Sync error: " + ex.Message, EventLogEntryType.Error);
			}
		}
	}
}
